from django import forms
from django.db.models import fields
from django.forms import widgets
from web import models
from web.forms.bootstrap import BootStrapForm

class ColorRadioSelect(widgets.ChoiceWidget):
    input_type = 'radio'
    template_name = 'web/widgets/color_radio/input.html'
    option_template_name = 'web/widgets/color_radio/input_option.html'

class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude=['color']
    def __init__(self, request, *args, **kwargs):
        # self.bootstrap_class_exclude=['color']
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta:
        model= models.Project
        fields = ['name', 'color','desc']
        widgets = {
            'desc': widgets.Textarea(attrs={}),
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }
        
    def clean_name(self):
        name = self.cleaned_data['name']
        # 同一用户有相同项目名称
        _existed = models.Project.objects.filter(name=name, creator = self.request.tracer.user).exists() 
        if _existed:
            self.add_error('name','项目名称重复')
        count = models.Project.objects.filter(creator = self.request.tracer.user).count()
        if self.request.tracer.price_policy.project_num <= count:
            self.add_error('name','项目数量超过限制，请购买会员')
            
        # 超过项目数量    
        
        return name


        